"use strict";
const electron = require("electron");
const { screen, shell } = require('electron');
const { app, BrowserWindow, ipcMain } = require("electron");
const fs = require('fs');
const path = require('path');
const os = require('os');
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib';
let opsWindow, opsParams;
const isDevelopment = process.env.NODE_ENV !== "production";
const storePath = path.join(os.homedir(), '.my-electron-app-token.json');

function createOPSWindow() {
  const { width, height } = electron.screen.getPrimaryDisplay().workAreaSize;
  console.log("Creating OPS window", width, height);
  opsWindow = new BrowserWindow({
    width,
    height,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
      enableRemoteModule: true,
      webSecurity: false,
      allowRunningInsecureContent: true,
      webviewTag: true,
    },
    resizable: true,
    transparent: false,
    fullscreen: false,
    frame: true,
  });

  if (isDevelopment) {
    opsWindow.loadURL(`http://localhost:8080/#/login?${opsParams}`);
  } else {
    opsWindow.loadURL(`app://./index.html#/login?${opsParams}`);
  }

  opsWindow.on("closed", () => {
    opsWindow = null;
  });

  // wjh
  // opsWindow.webContents.once('did-finish-load', () => {
  //   opsWindow.webContents.send('init-data', treeLevelCurrentId);
  // });

  opsWindow.setMenuBarVisibility(false);

  opsWindow.maximize();

  opsWindow.on("maximize", () => {
  });

  opsWindow.on("unmaximize", () => {
    const newWidth = 1600;
    const newHeight = 800;

    const x = Math.round((width - newWidth) / 2);
    const y = Math.round((height - newHeight) / 2);

    opsWindow.setBounds({ width: newWidth, height: newHeight, x, y });
  });
}

// 处理文件操作的 IPC 事件
ipcMain.handle('get-token', () => {
  try {
    const data = fs.readFileSync(storePath, 'utf8');
    const json = JSON.parse(data);
    return json.token || '';
  } catch (e) {
    return '';
  }
});

ipcMain.handle('set-token', (event, token) => {
  const data = { token };
  fs.writeFileSync(storePath, JSON.stringify(data, null, 2));
});

ipcMain.handle('clear-token', () => {
  if (fs.existsSync(storePath)) {
    fs.unlinkSync(storePath);
  }
});

ipcMain.on('close-ops-window', (event) => {
  if (opsWindow) {
    opsWindow.close();
  }
});

ipcMain.on('shrink-ops-window', (event) => {
  if (opsWindow) {
    opsWindow.minimize();
  }
});

ipcMain.on('maximize-ops-window', (event) => {
  if (opsWindow) {
    if (opsWindow.isMaximized()) {
      const { width, height } = screen.getPrimaryDisplay().workAreaSize;

      const winWidth = 1600;
      const winHeight = 800;
      const x = Math.round((width - winWidth) / 2);
      const y = Math.round((height - winHeight) / 2);

      opsWindow.setBounds({ x, y, width: winWidth, height: winHeight });
    } else {
      opsWindow.maximize();
    }
  }
});

ipcMain.on('broadcast-window-close', () => {
  if (opsWindow) {
    opsWindow.close();
  }
});

ipcMain.on('open-url', (event, url) => {
  shell.openExternal(url);
});

ipcMain.on('open-image', (event, url) => {
  shell.openExternal(url);
});

function listenOPSWindowEvents() {
  ipcMain.on('open-ops-window', (event, args) => {
    const { loginUrl } = args;
    if (!opsWindow) {
      opsParams = loginUrl;
      createOPSWindow();
    } else {
      if (opsWindow.isMinimized()) {
        opsWindow.restore();
      }
      opsWindow.focus();
    }
  });
}

export { listenOPSWindowEvents };